<template>
	<view>
		<uni-popup ref="popup" :safe-area="false"  :style="{zIndex: props.zIndex}" @change="changePopup">
			<view class="bottom-popup">
				<view class="popup-title d-flex d-r psr a-center j-center">
					<view v-if="backShow" class="left_box d-flex d-r a-center j-center" @tap="closeDetails">
						<image src="/static/image/drinkWater-back.png" class="back"></image>
					</view>
					<view v-else @tap="showDateTable" class="left_box  d-flex d-r a-center" style="width:auto;padding-left: 20rpx;text-align: center;">
						<view>
							<view style="text-align: center;font-size: 26rpx;">{{moment(selectDate).format("M月D日")}}</view>
							<view style="text-align: center;font-size: 26rpx">{{moment(selectDate).locale('zh-cn').format('dddd')}}</view>
						</view>
					</view>
					<view class="title-text"><text class="title-text-text">喝水打卡</text></view>
					<view class="right_box d-flex d-r a-center j-center">
						<image @tap="close" class="title-icon" src="@/static/image/close.png"></image>
					</view>
					
				</view>
				<view class="popup-content">
					<view class="popup-describe">
						<view class="popup-describe-text">建议您今日喝水{{props.totalWater}}ml&nbsp;&nbsp;每次不超过500ml</view>
						<view class="d-flex d-r a-center j-center">
							<text class="popup-describe-text">今日已喝水{{count}}次，共{{countMeasure}}ml&nbsp;</text>
							<text @tap="showRecordPopup" class="popup-describe-link">查看详情</text>
						</view>
						<!--
						<view class="popup-describe-prompt">点击记录饮水量，可多选</view>
						-->
					</view>
					<view class="popup-measure d-flex d-r a-center j-center">
						<text class="popup-measure-text">共计</text>
						<view class="popup-measure-value">
							<text class="measure-value-number">{{measure}}</text>
							<view class="measure-value-line"></view>
						</view>
						<text class="popup-measure-text">ml(多选)</text>
					</view>
					<view class="popup-button d-flex d-r a-center j-between wrap">
						<template v-for="(item,index) in waterVolume" :key="index">
							<view @tap="clickWater(index)" :class="`button-piece d-flex a-center j-center ${item.state?'piece-yes':'piece-no'}`">
								<text :class="`piece-text ${item.state?'text-yes':'text-no'}`">{{item.measure}}ml</text>
							</view>
						</template>
					</view>
					<view class="d-flex a-center j-center">
						<view v-if="!addDisable" @tap="determine" :class="`custom-button d-flex d-r a-center j-center ${measure==0?'disabled-yes':'disabled-no'}`" >
							<text class="button-text">打卡</text>
						</view>
						<view v-else :class="`custom-button d-flex d-r a-center j-center disabled-yes`" >
							<text class="button-text">打卡</text>
						</view>
					</view>
				</view>
				<view class="record-popup" :class="{active:active}">
					<view class="popup-describe">
						<view class="popup-describe-text">建议您今日喝水{{props.totalWater}}ml&nbsp;&nbsp;每次不超过500ml</view>
						<view class="d-flex d-r a-center j-center">
							<text class="popup-describe-text">今日已喝水{{count}}次，共{{countMeasure}}ml&nbsp;</text>
						</view>
					</view>
					<scroll-view  scroll-y="true" style="height: 623rpx;">
						<view class="popup-row">
							<template v-for="(item,index) in waterRecord" :key="index">
								<view class="data-row d-flex d-r a-center j-between">
									<text class="data-row-index">第{{item.index}}次</text>
									<text class="data-row-number">{{item.water}}ml</text>
									<view class="d-flex d-r a-center j-between">
										<text class="data-row-date">{{item.createTime}}</text>
										<image @tap="delWater(index)" class="data-row-del" src="@/static/image/checkPopup-del.png"></image>
									</view>
								</view>
							</template>
						</view>
					</scroll-view>
				</view>
			</view>
		</uni-popup>
	</view>
	<dateTable
		ref="datePopup"
		:markDate="markDate"
		:initialDate="selectDate"
		color="#1DC691"
		minDate="2023-1-1"
		:zIndex="999"
		:maxDate="moment().format('YYYY-MM-DD')"
		@onGetDate="onGetDate"
		@changeMoon="onChangeMoon">
	</dateTable>
</template>

<script setup lang="ts">
import { ref, defineEmits,nextTick } from "vue";
import { addGroupWaterRecord,getGroupFoodRecord,getGroupFoodDate } from "@/api/api";
import { userData as userDataStore } from "@/store/userData";
import moment from "moment";
import { numToChinese } from "@/utils/format";
import dateTable from "@/components/dateTable.vue";

interface Props {
	totalWater:number
	zIndex?:number
	groupId?:string,
	recordDate?:any
}
const props = withDefaults(defineProps<Props>(), {
	totalWater:0,
	zIndex:500,
	groupId:'',
	recordDate:moment()
})
const userData: any = userDataStore();
const popup = ref()
const open = () => {
	isDetermine = false;
	refreshWaterRecord()
	popup.value.open("bottom");
	nextTick(()=>{
		selectDate.value = props.recordDate;
		isAddDisable();//设置按钮是否可用
	});
}
const close = () => {
	popup.value.close();
}
const waterVolume = ref([
	{
		measure:50,
		state:false,
	},{
		measure:100,
		state:false,
	},{
		measure:200,
		state:false,
	},{
		measure:300,
		state:false,
	},{
		measure:400,
		state:false,
	},{
		measure:500,
		state:false,
	},{
		measure:800,
		state:false,
	},{
		measure:1000,
		state:false,
	},
]);
const count = ref(0);//喝水次数
const countMeasure = ref(0);//已喝水总量
const waterRecord:any = ref([]);//喝水记录
const refreshWaterRecord = () => {
	let params = {
		userId:userData.id,
		groupId:props.groupId,
		recordDate:moment().format("YYYY-MM-DD"),
		type:5,
	}
	countMeasure.value = 0;
	getGroupFoodRecord(params).then((res:any) => {
		if(res.success){
			waterRecord.value = res.data.userHealthRecordDetails;
			if(waterRecord.value.length==0){
				popup.value.open("bottom");
				//recordPopup.value.close();
			}
			count.value = res.data.userHealthRecordDetails.length;
			res.data.userHealthRecordDetails.forEach((item:any,index:number) => {
				item.index = numToChinese(index+1);
				item.createTime = moment(item.createTime,"YYYY-MM-DD HH:mm:ss").format("M月D日HH:mm");
				countMeasure.value += item.water;
			});
		}
	});
}
const measure = ref(0);
const clickWater = (index:number) => {
	waterVolume.value[index].state = !waterVolume.value[index].state;
	let count = 0;
	waterVolume.value.forEach((res:any) => {
		if(res.state)count+=res.measure;
	});
	measure.value = count;
}
const emit = defineEmits(["submitWater"]);
let isDetermine  = false;//防止重复点击
const determine = () => {
	if(isDetermine||measure.value ===0)return;
	isDetermine = true;
	
	let total = 0;
	let userHealthRecordDetails:any = [];
	waterRecord.value.forEach((item:any) => {
		let obj = JSON.parse(JSON.stringify(item));
		userHealthRecordDetails.push({
			water:obj.water,
			unit:"ml"
		});
		total += obj.water;
	})
	userHealthRecordDetails.push({
		water:measure.value,
		unit:"ml"
	});
	total += measure.value;
	let params = {
		groupId:props.groupId,
		userId:userData.id,
		waterTotal:total,
		recordDate:moment().format("YYYY-MM-DD"),
		type:5,
		userHealthRecordDetails:userHealthRecordDetails
	};
	addGroupWaterRecord(params).then((res:any) => {
		if(res.success){
			uni.showToast({
			    title: "喝水打卡成功",  
			    icon: 'success',  
			    duration: 1500,
			});
			close();
			waterVolume.value.forEach((res:any) => {
				res.state  =false;
			});
			measure.value = 0;
		}else{
			isDetermine = false;
			uni.showToast({
			    title: res.message,  
			    icon: 'none',  
			    duration: 1500,
			});
		}
	});
}
const active = ref(false);
const showRecordPopup = () => {
	setTimeout(()=>{
		active.value = true;
	},100);
	setTimeout(()=>{
		backShow.value = true;
	},400);
}
const backShow = ref(false);
const closeDetails = () =>{
	backShow.value = false;
	active.value = false;
}
const changePopup = (e:any) => {
	if(!e.show){
		closeDetails();
		emit("submitWater");
	}
}
const delWater = (index:number) => {
	count.value --;
	waterRecord.value.splice(index, 1);
	let total = 0;
	let userHealthRecordDetails:any = [];
	waterRecord.value.forEach((item:any) => {
		let obj = JSON.parse(JSON.stringify(item));
		userHealthRecordDetails.push({
			water:obj.water,
			unit:"ml"
		});
		total += obj.water;
	})
	let params = {
		groupId:props.groupId,
		userId:userData.id,
		waterTotal:total,
		recordDate:moment().format("YYYY-MM-DD"),
		type:5,
		userHealthRecordDetails:userHealthRecordDetails
	};
	
	addGroupWaterRecord(params).then((res:any) => {
		if(res.success){
			uni.showToast({
			    title: res.message,
			    icon: 'success',  
			    duration: 1500,
			});
			refreshWaterRecord();
		}
	});
}
const selectDate:any = ref(new Date());//选中的日期
const markDate:any = ref([])//需要标识的日期
const datePopup = ref();
//日期选择
const showDateTable = () => {
	onChangeMoon(selectDate.value);//查询需要高亮显示的日期
	datePopup.value.open()
}
//日期选择器月份变更时操作
const onChangeMoon = (date:any) => {
	markDate.value = [];
	let param = {
		userId:userData.id,
		type:5,
		groupId:props.groupId,
		recordDate:moment(date).format("YYYY-MM-DD"),
	}
	getGroupFoodDate(param).then((res:any) => {
		res.data.forEach((item:any) => {
			markDate.value.push(item.recordDate)
		})
	})
}
const onGetDate = (date:Date) => {
	selectDate.value = date;
	refreshWaterRecord();//重新加载数据
	isAddDisable();//设置按钮是否可用
}
//判断添加按钮是否可用
const addDisable = ref(false);//添加按钮是否可用
const isAddDisable = () => {
	
	//设置多少天内可修改
	var threeDaysAgo = moment().subtract(3, 'days');    
	var today = moment();  
	
	var dateToCheck = moment(selectDate.value); // 这是你要检查的日期  
	  
	if (dateToCheck.isBetween(threeDaysAgo, today)) {  
		addDisable.value = false;
	} else {  
		addDisable.value =  true;
		uni.showToast({
		    title: "三天前的记录仅可查看",  
		    icon: 'none',  
		    duration: 2000,
		});
	}
}
defineExpose({
  open,
  close
});
</script>

<style lang="scss" scoped>
.a-center {
    align-items: center;
}

.j-center {
    justify-content: center;
}

.j-between {
    justify-content: space-between;
}
.j-end {
    justify-content: flex-end;
}

.j-around {
    justify-content: space-around;
}

.d-flex d-r {
    display: flex;
}

.d-c {
    flex-direction: column;
}
.d-r {
    flex-direction: row;
}
.wrap {
    flex-wrap: wrap;
}
.j-end {
    justify-content: flex-end;
}

.bottom-popup{
	position: relative;
	background: #FFFFFF;
	border-radius: 20rpx 20rpx 0rpx 0rpx;
	padding-bottom: 60rpx;
	.popup-title{
		height: 100rpx;
		/*box-shadow: 0rpx -2rpx 8rpx 0rpx rgba(0,0,0,0.1);*/
		/*border-bottom: 1rpx solid #E4E4E4;*/
		.left_box{
			position: absolute;
			top:0;
			left: 0;
			width: 100rpx;
			height: 100rpx;
			.back{
				width: 48rpx;
				height: 48rpx;
			}
		}
		.title-text{
			text-align: center;
			.title-text-text{
				font-size: 34rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
			}
		}
		.right_box{
			position: absolute;
			top:0;
			right: 0;
			width: 100rpx;
			height: 100rpx;
			.title-icon{
				width: 36rpx;
				height: 36rpx;
			}
		}
	}
	.popup-content{
	}
	.record-popup{
		background: #FFFFFF;
		position: absolute;
		left:0;
		bottom: 0;
		width: 750rpx;
		height: 645rpx;
		transform: translateX(750rpx);
		transition: transform .4s linear;
		&.active{
		    transform: translateX(0rpx);
		}
	}
	.popup-describe{
		padding: 25rpx 0 0 0;
		height: 105rpx;
		.popup-describe-text{
			text-align: center;
			font-size: 30rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #333333;
		}
		.popup-describe-link{
			font-size: 30rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #1DC691;
			text-decoration: underline;
		}
		.popup-describe-prompt{
			text-align: center;
			padding-top: 13rpx;
			font-size: 30rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #666666;
		}
	}
	.popup-measure{
		padding-top: 35rpx;
		height: 100rpx;
		.popup-measure-text{
			padding-top: 30rpx;
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #999999;
		}
		.popup-measure-value{
			.measure-value-number{
				padding: 0 40rpx;
				font-size: 60rpx;
				font-family:'din',DINAlternate, DINAlternate;
				font-weight: bold;
				color: #1DC691;
				
			}
			.measure-value-line{
				margin-top: -10rpx;
				height: 2rpx;
				background: #59EDBF;
			}
		}
	}
	.popup-button{
		padding: 15rpx 30rpx 30rpx 30rpx;
		.button-piece{
			margin-top: 15rpx;
			width: 160rpx;
			height: 120rpx;
			border-radius: 10rpx;
			.piece-text{
				font-size: 28rpx;
			}
			.text-yes{
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
			}
			.text-no{
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
			}
		}
		.piece-yes{
			background: #23E2A6;
		}
		.piece-no{
			border: 1rpx solid #CCCCCC;
		}
	}
	.custom-button{
		width: 690rpx;
		height: 80rpx;
		border-radius: 20rpx;
		.button-text{
			font-size: 32rpx;
			font-family: PingFangSC-Semibold, PingFang SC;
			font-weight: 600;
			color: #FFFFFF;
		}
	}
	.disabled-yes{
		background: #ABABAB;
	}
	.disabled-no{
		background: linear-gradient(to right,#29DBA3, #64F1C5);
	}
	.popup-row{
		padding:33rpx 30rpx 0 30rpx;
		.data-row{
			height: 80rpx;
			.data-row-index{
				font-size: 30rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
			}
			.data-row-number{
				font-size: 30rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #1DC691;
			}
			.data-row-date{
				padding-right: 30rpx;
				font-size: 24rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #999999;
			}
			.data-row-del{
				width: 40rpx;
				height: 40rpx;
			}
		}
	}
}
</style>